package com.ruoyi.web.cp.service.rm;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.google.common.collect.Lists;
import com.ruoyi.web.core.config.ConfigLoader;
import com.ruoyi.web.cp.domain.rm.RmGame;
import com.ruoyi.web.cp.domain.rm.RmResult;
import com.ruoyi.web.cp.service.WinxinService;
import com.ruoyi.web.mapper.RmGameMapper;
import com.ruoyi.web.mapper.RmResultMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xiesm
 * @Description: TODO
 * @date 2025-07-21 16:39
 */
@Slf4j
@Service
public class RmobResult3MergeService {
    @Autowired
    private RmResultMapper rmResultMapper;
    @Autowired
    private RmGameMapper rmGameMapper;
    @Autowired
    private WinxinService winxinService;
    @Autowired
    private ConfigLoader configLoader;

    @SneakyThrows
    public void merge(int days, String name) {
        try {
            List<RmGame> rmGames = rmGameMapper.selectLastNDays(days);
            if (CollUtil.isEmpty(rmGames)) {
                return;
            }
            List<String> gameIds = rmGames.stream().map(RmGame::getGameId)
                    .distinct().collect(Collectors.toList());

            List<RmResult> rmResults = rmResultMapper.selectByGameIds(gameIds);
            Map<String, RmResult> gameIdToRmResultMap = rmResults.stream().collect(Collectors.toMap(
                    RmResult::getGameId,
                    v -> v,
                    (existing, replacement) -> existing
            ));


            String path = configLoader.getRmPath() + name + ".xlsx";
            File tempFile = new File(path);
            // 如果文件已存在，先删除
            if (tempFile.exists()) {
                FileUtil.del(tempFile);
            }
            // 导出到 Excel
            exportRmobDoubleMergeToExcel(rmGames, gameIdToRmResultMap, tempFile);
            winxinService.uploadMediaByAppAndSendMsg("1000018", path);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public void exportRmobDoubleMergeToExcel(List<RmGame> rmGames, Map<String, RmResult> gameIdToRmResultMap, File tempFile) {
        // 创建 ExcelWriter 对象
        ExcelWriter writer = ExcelUtil.getWriter(tempFile);

        // 手动设置表头
        String[] headers = {"日期", "联赛", "主队", "客队", "RM反00",
                "OB双进", "OB波胆00", "半场大小球", "全场大小球", "独赢主赔率",
                "独赢平赔率", "独赢客赔率", "亚盘半场让球", "亚盘半场让球上盘", "亚盘半场让球下盘",
                "亚盘全场让球", "亚盘全场让球上盘", "亚盘全场让球下盘",
                "半场结果", "全场结果", "首进球时间"
        };
        writer.writeHeadRow(Arrays.asList(headers));

        // 写入数据（假设 RmobDoubleMerge 有对应的 getter 方法）
        for (RmGame rmGame : rmGames) {
            List<String> row = Lists.newArrayList();
            row.add(rmGame.parseDateStr());       // 日期
            row.add(rmGame.getLeague());          // 联赛
            row.add(rmGame.getTeamA());           // 主队
            row.add(rmGame.getTeamB());          // 客队

            List<RmGame.Detail> allPlvs = rmGame.allPlvFromJson();
            String rm00 = "";
            if (CollUtil.isNotEmpty(allPlvs)) {
                Map<String, String> allPlvDict = allPlvs.stream().collect(Collectors.toMap(
                        RmGame.Detail::getScore,
                        RmGame.Detail::getPlv,
                        (existing, replacement) -> existing
                ));
                rm00 = allPlvDict.get("0-0");
            }
            row.add(rm00);

            RmGame.ObDetail obPlvs = rmGame.obPlvFromJson();
            if (obPlvs != null) {
                row.add(obPlvs.getDouble_plv());
                row.add(obPlvs.getBdan00_plv());
                row.add(obPlvs.getGoal_half_desc());
                row.add(obPlvs.getGoal_desc());
                row.add(obPlvs.getWin_plv());
                row.add(obPlvs.getDraw_plv());
                row.add(obPlvs.getLose_plv());
                row.add(obPlvs.getAsian_half_desc());
                row.add(obPlvs.getAsian_half_big_plv());
                row.add(obPlvs.getAsian_half_small_plv());
                row.add(obPlvs.getAsian_desc());
                row.add(obPlvs.getAsian_big_plv());
                row.add(obPlvs.getAsian_small_plv());
            } else {
                for (int i = 0; i < 13; i++) {
                    row.add("");
                }
            }

            RmResult rmResult = gameIdToRmResultMap.get(rmGame.getGameId());
            if (rmResult != null) {
                row.add(rmResult.getHalfScore());
                row.add(rmResult.getAllScore());
                row.add(rmResult.getGoalTime());
            } else {
                for (int i = 0; i < 3; i++) {
                    row.add("");
                }
            }

            writer.writeRow(row);
        }
        int[] columnWidths = {
                18 * 256, // 日期
                15 * 256, // 联赛
                20 * 256, // 主队
                20 * 256, // 客队
                12 * 256, // 半场结果
                12 * 256, // 全场结果
                12 * 256,
                12 * 256,
                12 * 256,
                12 * 256,
                12 * 256,
                12 * 256,
                12 * 256,
                12 * 256,
                12 * 256,
                12 * 256,
                12 * 256,
                12 * 256,
                12 * 256,
                20 * 256,
                20 * 256,
                20 * 256,
                20 * 256,
                20 * 256,
                12 * 256,
                12 * 256,
                12 * 256
        };

        for (int i = 0; i < columnWidths.length; i++) {
            writer.getSheet().setColumnWidth(i, columnWidths[i]);
        }
        // 关闭流
        writer.close();
    }
}
